<template>
	<a-modal v-model:open='open' :key="key" :title='isEdit ? $t("编辑") : $t("New")' width="50%" :destroyOnClose="true"
		:maskClosable="false" @afterClose='handleClose'>
		<a-spin :spinning="spinning">
			<a-form layout="vertical" :model="formState" ref="formRef" :rules="rules">
				<div class="user-row">
					<div class="user-row-content">
						<a-row :gutter="[16, 16]">
							<a-col :span="12">
								<a-form-item :label="$t('员工')">
									<a-select :getPopupContainer="(triggerNode: any) => triggerNode.parentNode" v-model:value="formState.employeeId" :default-active-first-option="false"
										show-search :not-found-content="null" :show-arrow="false" :filter-option="false"
										@search="fetchUser" :options="users"
										:fieldNames="{ label: 'fullName', value: 'id' }" :placeholder="$t('输入用户名')"
										@change="handleSelect">
										<template v-if="fetching" #notFoundContent>
											<a-spin size="small" />
										</template>
									</a-select>

								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item :label="$t('用户名')" name="username">
									<a-input v-model:value="formState.username" />
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item :label="$t('邮箱')" name="email">
									<a-input v-model:value="formState.email" :disabled="isEdit"
										:placeholder="$t('输入邮箱')" />
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item :label="$t('姓名')" name="firstName">
									<a-input v-model:value="formState.firstName" :placeholder="$t('输入姓名')" />
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item :label="$t('姓氏')" name="lastName">
									<a-input v-model:value="formState.lastName" :placeholder="$t('输入姓氏')" />
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item :label="$t('性别')" name="gender">
									<a-select :getPopupContainer="(triggerNode: any) => triggerNode.parentNode" v-model:value="formState.gender" :placeholder="$t('选择性别')">
										<a-select-option v-for="(gender) in genders" :value="gender.dictData"
											:key="gender.dictData">{{
												isCn ? gender.descZh : isEn ? gender.dictDesc : gender.descAr
											}}</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item :label="$t('电话')" name="phone">
									<a-input v-model:value="formState.phone" :placeholder="$t('输入电话')" />
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item :label="$t('状态')" name="status">
									<a-select :getPopupContainer="(triggerNode: any) => triggerNode.parentNode" v-model:value="formState.status" :placeholder="$t('选择状态')">
										<a-select-option v-for="(st) in statusLists" :value="st.dictData"
											:key="st.dictData">{{
												isCn ? st.descZh : isEn ? st.dictDesc : st.descAr }}</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>
							<a-col :span="24">
								<a-form-item :label="$t('部门')" name="deptIdList">
									<a-select :getPopupContainer="(triggerNode: any) => triggerNode.parentNode" v-model:value="formState.deptIdList" mode="multiple"
										:placeholder="$t('选择部门')">
										<a-select-option v-for="(department) in departments" :value="department.id"
											:key="department.id">{{
												showCurrentLang(department, isCn, isEn, isArabic)
											}}</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>
							<!-- <a-col :span="12">
							<a-form-item :label="$t('工作')" prop="job">
								<a-input v-model:value="formState.job" :placeholder="$t('输入工作')" />
							</a-form-item>
						</a-col> -->
							<a-col :span="24">
								<a-form-item :label="$t('角色')" name="role">
									<a-select :getPopupContainer="(triggerNode: any) => triggerNode.parentNode" v-model:value="formState.roleIdList" :placeholder="$t('选择角色')"
										mode="multiple" max-tag-count="2">
										<a-select-option v-for="(role) in roles" :value="role.id" :key="role.id">{{
											isCn ? role.nameZh : isEn ? role.nameEn : role.nameAr }}</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>

							<a-col v-if="!isEdit" :span="12">
								<a-form-item :label="$t('密码')" name="password">
									<a-input-password v-model:value="formState.password" :placeholder="$t('请输入密码')" />
								</a-form-item>
							</a-col>
							<a-col v-if="!isEdit" :span="12">
								<a-form-item :label="$t('确认密码')" name="password2">
									<a-input-password v-model:value="formState.password2" :placeholder="$t('请输入密码')" />
								</a-form-item>
							</a-col>
						</a-row>
					</div>
				</div>
			</a-form>
			<div class="tips">
				{{ $t("密码规则") }}
				<div>{{ $t("字符数量") }}
				</div>
				<div> {{ $t("字符强度") }}
				</div>
			</div>

		</a-spin>
		<template #footer>
			<a-button key='back' @click='handleClose'>{{ $t('关闭') }}</a-button>
			<a-button key='submit' type='primary' :loading='loading' @click='handleOk'>{{ $t('保存')
				}}</a-button>
		</template>
	</a-modal>
</template>
<script lang='ts' setup>
import { ref, watch, onMounted, computed, nextTick } from "vue";
import { useI18n } from 'vue-i18n';
import { message } from 'ant-design-vue';
import { getDepartmentLists, getUserInfo, queryUsers } from '@/api/user'
import { queryUserInfo } from '@/api/staff/staffApi'
import { GetSysUserAdd, PutSysUserUpdate, queryDictKey, queryUsersInfo } from "@/api/user/index";
import { isEmail, isStrongPassword } from '@/utils/validate'
import { AES_ECB_ENCRYPT } from '@/utils/encrypt'
import { useLanguage } from "@/hooks/index"
import { showCurrentLang } from "@/utils/common/common"
import { queryRolesListsNoPage, QueryUserRoles, QueryUserDepartment } from '@/api/setting'
import { throttle } from "echarts";
const { isEn, isCn, isArabic } = useLanguage()
const { t: $t } = useI18n();
const store = useStore();
const emit = defineEmits(['ok', 'close', 'update:visible'])
const loading = ref(false)
let title = ref('')
let employee = ref("")
let spinning = ref(false)
let fetching = ref<boolean>(false)
let _cache = ""
let _departmentCache = ""
const props = defineProps({
	visible: {
		type: Boolean,
		required: true,
		default: false
	},
	uid: {
		type: String,
		required: true,
		default: ''
	},
	userId: {
		type: String,
		required: true,
		default: ''
	},
})
const open = computed({
	get() {
		return props.visible
	},
	set(value) {
		emit('update:visible', value)
	}
})
const isEdit = computed(() => {
	if (props.uid.length) return true
	return false
})
const basicData = {
	email: '',
	username: '',
	password: '',
	password2: '',
	deptId: '',
	firstName: '',
	lastName: '',
	phone: '',
	employeeId: null,
	roleIdList: [],
	deptIdList: [],
	gender: '',
	status: '',
	job: '',
	id: ''
}
let roles = ref([])
let genders = ref([])
let statusLists = ref([])
let departments = ref([])
let users = ref([])
let key = ref(1)
const formRef = ref(null)
const formState = ref(cloneDeep(basicData));
const getDetail = async () => {
	spinning.value = true
	const { data } = await getUserInfo(props.uid).finally(() => {
		spinning.value = false
	})
	formState.value = cloneDeep(data)
	formState.value.status = String(formState.value.status)
	if (formState?.value?.employeeId) {
		users.value = [
			{
				id: formState.value?.employeeId,
				fullName: `${formState.value.username}  (${formState.value.email})`,
			}
		]
	}
	
}
const fetchUser = debounce(async (value) => {
	const params = {
		keyword: value,
		fromSystemUser: true
	}
	if (value.length < 1) return
	fetching.value = true
	const { data } = await queryUsers(params).finally(() => {
		fetching.value = false
	})
	users.value = data.map(v => {
		if (v.workEmail) {
			v.fullName = `${v.fullName}  (${v.workEmail})`
		}
		return v
	})

	if (isEdit.value) users.value = users.value.filter(i => {
		if (i?.workEmail && i.workEmail == formState.value.email) return true
		return false
	})
}, 1000)
const getDepartments = async () => {
	const { data } = await getDepartmentLists({})
	departments.value = data ?? []
}
// const handleBlur = (value) => {
// 	const data = value.target.value
// 	if (!data) return
// 	formState.value.username = data ?? ''
// }
const handleSelect = async (value) => {
	const item = users.value.find(item => item.id === value)
	const { data } = await queryUserInfo(item.id)
	formState.value.data = String(data.gender) ?? ''
	formState.value.lastName = String(data.lastName) ?? ''
	formState.value.firstName = String(data.firstName) ?? ''
	formState.value.phone = data?.phone ?? ''
	formState.value.status = data?.status ?? ''
	// formState.value.email = data?.personalEmail ?? ''
	formState.value.employeeId = data?.id
}
const init = async () => {
	const statusData = await queryDictKey('systemUserStatus')
	statusLists.value = statusData?.data ?? []
	const genderData = await queryDictKey('gender')
	genders.value = genderData?.data ?? []
	const { data } = await queryRolesListsNoPage()
	roles.value = data
}
const getUserRole = () => {
	nextTick(async () => {
		spinning.value = true
		const { data } = await QueryUserDepartment({ userId: props.userId }).finally(() => {
			spinning.value = false
		})
		formState.value.deptIdList = []
		data.forEach(i => {
			formState.value.deptIdList.push(i.deptId)
		})
	})
	_cache = JSON.stringify(formState.value.deptIdList)
}
const getUserDepartment = () => {
	nextTick(async () => {
		spinning.value = true
		const { data } = await QueryUserRoles({ userId: props.userId }).finally(() => {
			spinning.value = false
		})
		formState.value.roleIdList = []
		data.forEach(i => {
			formState.value.roleIdList.push(i.roleId)
		})
	})
	_departmentCache = JSON.stringify(formState.value.roleIdList)
	key.value++
}
const queryEmplayeeInfo = () => {
	setTimeout(async () => {

	}, 1000)
}
watch(() => open,
	(newVal, oldVal) => {
		if (newVal.value && props.uid.length) {
			title.value = $t('编辑')
			// 调用详情接口
			getDetail()
			getUserRole()
			getUserDepartment()
		} else {
			title.value = $t('新增')
			formState.value = cloneDeep(basicData)
		}
		getDepartments()
		init()
	},
	{
		deep: true,
		immediate: true,
	}
)

const checkPassword2 = function (rule, value, callback) {
	if (value) {
		if (value !== formState.value.password) {
			return Promise.reject($t('密码不一致'))
		}
		else {
			return Promise.resolve();
		}
	}
	else {
		return Promise.reject($t('请输入'))
	}
}
const strongPassword = function (rule, value, callback) {
	if (value) {
		if (!isStrongPassword(value)) {
			return Promise.reject($t("密码强度"))
		}
		else {
			return Promise.resolve();
		}
	}
	else {
		return Promise.reject($t('请输入'))
	}
}
const rules = {
	email: [{ required: true, validator: isEmail, trigger: ['change', 'blur'] }],
	username: [{ required: true, message: $t('请输入'), trigger: ['change', 'blur'] }],
	firstName: [{ required: true, message: $t('请输入'), trigger: ['change', 'blur'] }],
	lastName: [{ required: true, message: $t('请输入'), trigger: ['change', 'blur'] }],
	deptId: [{ required: true, message: $t('请选择'), trigger: ['change', 'blur'] }],
	password: [{ required: true, validator: strongPassword, trigger: ['change', 'blur'] }],
	password2: [{ required: true, validator: checkPassword2, trigger: ['change', 'blur'] }],
	// phone: [{ required: true, message: $t('请输入'), trigger: ['change', 'blur'] }]
}

const handleOk = debounce(async () => {
	formRef.value.validate().then(async () => {
		if (isEdit.value) {
			const data = cloneDeep(formState.value)
			const ca = JSON.stringify(data.roleIdList)
			if (ca == _cache) data.roleIdList = []
			const _departmentCa = JSON.stringify(data.deptIdList)
			if (_departmentCa == _departmentCache) data.deptIdList = []
			loading.value = true
			await PutSysUserUpdate(data).finally(() => {
				loading.value = false
			})
			message.success($t('操作成功'))
			ok()
		} else {
			const data = cloneDeep(formState.value)
			const password = data.password
			const password2 = data.password2
			data.password = AES_ECB_ENCRYPT(password, data.email)
			data.password2 = AES_ECB_ENCRYPT(password2, data.email)
			loading.value = true
			await GetSysUserAdd(data).finally(() => {
				loading.value = false
			})
			message.success($t('操作成功'))
			ok()
		}
	}).catch((error: any) => {
		// consolelog('error', error);
	});
}, 1000)
const resetForm = () => {
	formRef.value.resetFields();
};
const clearValidates = () => {
	formRef.value.clearValidate();
};
const ok = () => {
	clearValidates()
	resetForm()
	emit('ok', open.value = false)
}
const handleClose = () => {
	clearValidates()
	resetForm()
	emit('update:visible', false)
}
</script>
<style lang='scss' scoped>
.ant-modal-content {
	.tips {
		font-size: 12px;

		div {
			text-indent: 1em;
		}
	}

	.saveButton {
		background-color: #18a689;
		color: #fff;
	}

	.saveButton:active {
		color: #fff !important;
		border-color: #fff !important;
	}
}
</style>